import React, { Component } from 'react';
import { getProducts } from '../../../api'
import { Table, Button, Space, Modal, Form, Input, Select } from 'antd'
import { connect } from 'react-redux'
import { setProducts, editProduct, delProducts } from '../../../store/actions'

class Index extends Component {
	state = {
		columns: [{
			title: '产品类型',
			key: 'type',
			dataIndex: 'type',
		},{
			title: '产品名称',
			key: 'title',
			dataIndex: 'title',
		}, {
			title: '产品描述',
			key: 'desc',
			dataIndex: 'desc'
		}, {
			title: '产品图片',
			key: 'url',
			dataIndex: 'url',
			render: (v) => {
				return <img src={v}></img>
			}
		}, {
			title: '产品单价',
			key: 'price',
			dataIndex: 'price'
		}, {
			title: '操作',
			key: 'opration',
			render: (v) => {
				return <Space>
					<Button type="primary" onClick={() => this.handleEdit(v)}>编辑</Button>
					<Button type="primary" danger onClick={ () => this.handleDelete(v) }>删除</Button>
				</Space>
			}
		}],
		currEdit: {},
		visible: false,
		type: ''
	}
	handleEdit(v) {
		this.setState({
			currEdit: v,
			visible: true
		})
	}
	handleCancel() {
		this.setState({
			visible: false,
		})
	}
	handleOk() {
		const { currEdit } = this.state
		this.props.dispatch(editProduct(currEdit))
		this.handleCancel()
	}
	handleDelete(v) {
		this.props.dispatch(delProducts(v))
	}
	componentDidMount() {
		this.props.products.length === 0 && this.props.dispatch(setProducts())
	}
	render() {
		const { columns, visible, currEdit, type } = this.state
		const { products } = this.props
		return (

			<div>
				<div>
					<Select style={{ width: 120 }} value={ type } onChange={ value => this.setState({ type: value })  }>
						<Select.Option value="">所有</Select.Option>
						<Select.Option value="吃的">吃的</Select.Option>
						<Select.Option value="电影">电影</Select.Option>
						<Select.Option value="衣服">衣服</Select.Option>
					</Select>
					{ type }
				</div>
				<Table columns={columns} dataSource={products.filter(v => v.type.includes(type))}></Table>
				<Modal visible={visible} okText="确定修改" cancelText="取消修改" title="修改"
					onOk={() => this.handleOk()}
					onCancel={() => this.handleCancel()}
				>
					<Input value={currEdit.title} onChange={e => this.setState({ currEdit: { ...currEdit, title: e.target.value } })} />
					<Input value={currEdit.price} onChange={e => this.setState({ currEdit: { ...currEdit, price: e.target.value } })} />
					<Input.TextArea value={currEdit.desc} onChange={e => this.setState({ currEdit: { ...currEdit, desc: e.target.value } })} />
				</Modal>
			</div>
		);
	}
}

export default connect(state => state, dispatch => ({ dispatch }))(Index);
